package com.np.storage_demo1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

public class SharedPreferencesActivity extends AppCompatActivity {

    public static final String FILE_NAME = "cache";
    public static final String NAME = "name";
    public static final String PASSWORD = "password";

    private EditText txtName;
    private EditText txtPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);

        txtName = findViewById(R.id.name);
        txtPassword = findViewById(R.id.password);

        // 打开的时候从SharedPreferences取出姓名和密码
        SharedPreferences settings = getSharedPreferences(FILE_NAME, 0); // 获取一个SharedPreferences对象
        String name = settings.getString(NAME, "admin");  // 取出保存的NAME
        String password = settings.getString(PASSWORD, "123456");  // 取出保存的PASSWORD
        txtName.setText(name);
        txtPassword.setText(password);
    }

    @Override
    protected void onStop() {
        super.onStop();

        // 关闭的时候将输入框中的姓名和密码保存到SharedPreferences，对应文件:/data/data/<package-name>/shared_prefs/cache.xml
        SharedPreferences settings = getSharedPreferences(FILE_NAME, 0);
        settings.edit()
                .putString(NAME, txtName.getText().toString())
                .putString(PASSWORD, txtPassword.getText().toString())
                .commit();
    }
}